<?php

namespace backend\models;

use common\models\HtCommon;
use Yii;

/**
 * This is the model class for table "{{%login_log}}".
 *
 * @property int $id
 * @property int $uid 登录用户
 * @property string $ip 登录IP
 * @property string $address 登录地址
 * @property int $login_time 登录时间
 */
class LoginLog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%login_log}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uid', 'ip', 'address'], 'required'],
            [['uid', 'login_time'], 'integer'],
            [['ip'], 'string', 'max' => 32],
            [['address'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'uid' => '登录用户',
            'ip' => '登录IP',
            'address' => '登录地址',
            'login_time' => '登录时间',
        ];
    }

    /**
     * 关联用户
     */
    public function getUser()
    {
        return $this->hasOne(User::className(),['id'=>'uid']);
    }

    /**
     * 登录日志
     * @param $uid
     */
    public static function log($uid)
    {
        $log = new LoginLog();
        $log->uid = $uid;
        $log->ip = Yii::$app->request->userIP;
        $res = HtCommon::getAddress($log->ip);
        $log->address = $res;
        $log->login_time = time();
        $log->save();
    }
}
